package io.zt.dangyuan;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.xutils.ex.HttpException;

import io.zt.dangyuan.customView.OnRefreshListener;
import io.zt.dangyuan.customView.RefreshListView;
import io.zt.dangyuan.object.ReadLoveModel;
import io.zt.dangyuan.object.ReadLoveRequest;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ReadLove extends BaseActivity implements OnRefreshListener {

    private RefreshListView listView;

    private EditText postion;
    private EditText setEditT;
    private TextView searchButton;
    private ReadLoveAdapter adapter;

    private List<ReadLoveModel.ReadLoveObject> listObejects;

    private ReadLoveRequest readLoveRequest;

    private Handler h = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            listView.hideFooterView();

//            Toast.makeText(ReadLove.this, "已经没有更多数据了，亲", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addCenterView(R.layout.activity_read_love);
        toolbar.setNavigationIcon(R.drawable.icon_select_all_light);
        setTitleImg(R.drawable.title_shuhai);

        listView = (RefreshListView) findViewById(R.id.activity_read_love_listview);
        postion = (EditText) findViewById(R.id.love_search_key1);
        setEditT = (EditText) findViewById(R.id.love_search_key2);
        searchButton = (TextView) findViewById(R.id.love_search_btn);

        listObejects = new ArrayList<ReadLoveModel.ReadLoveObject>();
        readLoveRequest = new ReadLoveRequest();

        readLoveRequest.setCurrpage(1);
        readLoveRequest.setPagesize(Constant.page);

        adapter = new ReadLoveAdapter(this, listObejects);

        listView.setAdapter(adapter);
        listView.setOnRefreshListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(ReadLove.this, ReadLoveDetailActivity.class);
                ReadLoveModel.ReadLoveObject object = listObejects.get(position - 1);

                intent.putExtra("userId", object.getUserid());
                startActivity(intent);
            }
        });
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listObejects.clear();
                webRequst(true);
            }
        });
//        webRequst(true);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_read_love, menu);
        menu.getItem(0).setIcon(R.drawable.icon_pre);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        if (id == R.id.action_woman) {
            readLoveRequest.setSex("0");
            listObejects.clear();
            webRequst(true);
            return true;
        } else if (id == R.id.action_man) {
            readLoveRequest.setSex("1");
            listObejects.clear();
            webRequst(true);
            return true;
        } else if (id == R.id.action_all) {
            readLoveRequest.setSex("");
            listObejects.clear();
            webRequst(true);
            return true;
        } else if (id == android.R.id.home) {
            startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDownPullRefresh() {
        listObejects.clear();
        readLoveRequest.setCurrpage(1);
        webRequst(false);
//        new AsyncTask<Void, Void, Void>() {
//
//            @Override
//            protected Void doInBackground(Void... params) {
//                listObejects.clear();
//                readLoveRequest.setCurrpage(1);
//                webRequst();
//                return null;
//            }
//
//            @Override
//            protected void onPostExecute(Void result) {
//                listView.hideHeaderView();
//            }
//        }.execute(new Void[]{});
    }

    @Override
    public void onLoadingMore() {

        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {

                if (readLoveRequest.isHasMoreData()) {
                    readLoveRequest.setCurrpage(readLoveRequest.getCurrpage() + 1);
                    webRequst(false);
                } else {
                    h.sendEmptyMessage(0);

                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                // 控制脚布局隐藏
//                listView.hideFooterView();
            }
        }.execute(new Void[]{});

    }


    public void webRequst(boolean ishow) {

        HashMap<String,Object> map = new HashMap<String,Object>();
        if (readLoveRequest.getSex() != null && !readLoveRequest.getSex().equals("")) {
            map.put("sex", readLoveRequest.getSex());
        }

        if (!TextUtils.isEmpty(setEditT.getText())) {

            String conmentStr = "";
            try {
                conmentStr = URLEncoder.encode(setEditT.getText().toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            map.put("username", conmentStr);
        }

        if (!TextUtils.isEmpty(postion.getText())) {
            String conmentStr = "";
            try {
                conmentStr = URLEncoder.encode(postion.getText().toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            map.put("workunit", conmentStr);
        }

        map.put("pagesize", String.valueOf(readLoveRequest.getPagesize()));
        map.put("currpage", String.valueOf(readLoveRequest.getCurrpage()));

        WebUtils.showProgress = ishow;
        WebUtils.sendPost(ReadLove.this, "list", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {

                ReadLoveModel resultData = JSON.parseObject(data, ReadLoveModel.class);
                listObejects.addAll(resultData.getList());
                adapter.notifyDataSetChanged();
                //判断是否还有数据，如果没有就不再重复加载
                if (resultData.getCount() < readLoveRequest.getPagesize()) {
                    readLoveRequest.setHasMoreData(false);
                }
                listView.hideHeaderView();
                listView.hideFooterView();
            }

            @Override
            public void onFailed(HttpException error, String msg) {
                listView.hideHeaderView();
                listView.hideFooterView();
            }
        });
    }
}
